// HelloController.java

package com.heima.springai.test;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

@RestController
public class HelloController {

    @GetMapping("/hello")
    public String hello(@RequestParam String name) {
        // 调用Python脚本
        String result = callPythonScript(name);
        return result;
    }

    private String callPythonScript(String name) {
        try {
            // 获取Python解释器的路径（根据你的系统可能需要修改）
            String pythonPath = "C:\\Users\\wangjianhua\\anaconda3\\python.exe";  // 或者使用完整路径，如 "/usr/bin/python3"
            // script.py的完整路径
            String scriptPath ="E:\\python_work\\.vscode\\script.py";  // 请替换为实际路径

            // 创建ProcessBuilder对象
            ProcessBuilder processBuilder = new ProcessBuilder(pythonPath, scriptPath, name);


            // 启动进程
            Process process = processBuilder.start();

            // 创建输入流读取Python的标准输出
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            StringBuilder output = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                output.append(line).append("\n");
            }

            // 创建输入流读取Python的错误输出
            BufferedReader errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
            StringBuilder errorOutput = new StringBuilder();
            String errorLine;
            while ((errorLine = errorReader.readLine()) != null) {
                errorOutput.append(errorLine).append("\n");
            }

            // 等待进程结束，并返回结果
            int exitCode = process.waitFor();
            if (exitCode != 0) {
                return "Error executing Python script. Exit code: " + exitCode + "\nError output: " + errorOutput.toString();
            }
            return output.toString();
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
            return "Error: " + e.getMessage();
        }
    }

}
